<template>
  <div class="upload_container">
    <div class="upload_body">
      <div
        :key="(item, i)"
        v-for="(item, i) in file"
        style="display: inline-block; margin-right: 10px; position: relative"
        class="imgList"
      >
        <img class="" :src="item" alt="" width="78px" height="78px" />
        <div class="imgList-cover">
          <Icon type="ios-close" @click="delImg(i)"></Icon>
        </div>
      </div>
      <Upload
        v-show="file.length < 3"
        ref="uploadImgRef"
        :show-upload-list="false"
        :format="fileFormats"
        :max-size="8192"
        name="file"
        action=""
        style="display: inline-block; width: 78px"
        :before-upload="beforeUpload"
        :on-exceeded-size="exceededSize"
      >
        <div style="cursor: pointer">
          <img
            src="../../assets/imgs/upload-img.png"
            width="78px"
            height="78px"
            alt=""
          />
        </div>
      </Upload>
    </div>
    <div
      class="upload_tips"
      style="font-size: 12px; text-align: left; color: #cdcdcf; width: 200px"
    >
      限3张图片，最大不超过8M
    </div>
  </div>
</template>

<script>
import {formatImg} from '@/utils/utils'
export default {
  name: "uploadImg",
  props: {
    update: {
      type: Object,
    },
  },
  watch: {
    update: {
      handler(newVal) {
        this.file = newVal.image || newVal.file || [];
      },
      immediate: true,
    },
  },
  components: {},
  data() {
    return {
      file: [],
      isUpload: false, // 是否上传成功
      fileFormats:['jpg', 'jpeg', 'png'], // 图片格式
    };
  },
  created() {},
  mounted() {},
  methods: {
    // 删除一张图片
    delImg(i) {
      this.file.splice(i, 1);
      this.isUpload = false;
    },
    // // 上传图片成功的回调
    // imghandleSuccess(res) {
    //   this.date.image.push(res.data[0])
    //   this.isUpload = false
    //   this.$emit('updateImg', {
    //     iamge: this.date.image,
    //     isUpload: this.isUpload,
    //   }) // 触发父组件自定义事件,接收参数
    // },
    // 上传图片前的回调
    async beforeUpload(file) {
      // 限制图片上传的格式
      if (!formatImg(file,this.fileFormats)) {
        this.$Message.error('不支持的文件格式! 只支持jpg, jpeg, png图片格式!')
        return false
      }
      this.isUpload = true;
      this.$emit("isUploadHandle", this.isUpload);
      let res = await this.compress(file);
      let uploadData = await this.updateFile(
        res.file,
        "file",
        "/api/manage/oss/upload"
      );
      if (uploadData.code != 200) {
        return this.$Message.error("图片上传失败,请稍后再试!");
      }
      if (uploadData.code == 200) {
        console.log(uploadData.data[0], "uploadData.data[0]");
        this.file.push(uploadData.data[0]);
        this.isUpload = false;
        this.$emit("updateImg", {
          iamge: this.file,
        });
        this.$emit("isUploadHandle", this.isUpload);
      }

      return false;
    },
    clearFiles() {
      this.$refs.uploadImgRef.clearFiles();
    },
    // 上传图片过大的钩子
    exceededSize() {
      this.$Message.error("上传图片过大,建议选择8M以下的图片!");
    },
    // 压缩图片的方法
    compress(file, size = 200, device = 4) {
      return new Promise((resolve) => {
        const reader = new FileReader(); // 创建 FileReader
        reader.onload = ({ target: { result: src } }) => {
          const fileSize = Number((file.size / 1024).toFixed(2));
          if (fileSize <= size) {
            resolve({
              file: file,
              origin: file,
              beforeSrc: src,
              afterSrc: src,
              beforeKB: fileSize + "KB",
              afterKB: fileSize + "KB",
              detail: [],
              quality: null,
            });
          } else {
            const image = new Image(); // 创建 img 元素
            image.onload = async () => {
              const canvas = document.createElement("canvas"); // 创建 canvas 元素
              canvas.width = image.width;
              canvas.height = image.height;
              canvas
                .getContext("2d")
                .drawImage(image, 0, 0, image.width, image.height); // 绘制 canvas
              let canvasURL, miniFile;
              let L = true;
              let quality = 0;
              const detail = [];
              let start = Date.now();
              for (let i = 1; i <= device; i++) {
                canvasURL = canvas.toDataURL(
                  "image/jpeg",
                  L ? (quality += 1 / 2 ** i) : (quality -= 1 / 2 ** i)
                );
                const buffer = atob(canvasURL.split(",")[1]);
                let length = buffer.length;
                const bufferArray = new Uint8Array(new ArrayBuffer(length));
                while (length--) {
                  bufferArray[length] = buffer.charCodeAt(length);
                }
                miniFile = new File([bufferArray], file.name, {
                  type: "image/jpeg",
                });
                miniFile.size / 1024 > size ? (L = false) : (L = true);
                detail.push({
                  quality,
                  size: miniFile.size,
                  kb: Number((miniFile.size / 1024).toFixed(2)),
                  time: Date.now() - start,
                });
                start = Date.now();
              }
              resolve({
                detail,
                quality,
                file: miniFile,
                origin: file,
                beforeSrc: src,
                afterSrc: canvasURL,
                beforeKB: Number((file.size / 1024).toFixed(2)),
                afterKB: Number((miniFile.size / 1024).toFixed(2)),
              });
            };
            image.src = src;
          }
        };
        reader.readAsDataURL(file);
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
